package com.hanfu.ucenter.web.web.service;

import com.hanfu.ucenter.web.bean.Member;
import com.hanfu.ucenter.web.bean.MemberSecurityLog;
import com.hanfu.ucenter.web.dao.MemberMapper;
import com.hanfu.ucenter.web.dao.MemberSecurityLogMapper;
import com.hanfu.ucenter.web.enums.UcenterEnum;
import com.hanfu.ucenter.web.exception.ErrorCode;
import com.hanfu.ucenter.web.exception.UCenterException;
import com.hanfu.ucenter.web.web.dto.Request.ReqMemberAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * Created by dufei on 19/9/18.
 */
@Service
public class MemberService {

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private MemberSecurityLogMapper memberSecurityLogMapper;


    public Member findByMemberId(Long id) throws UCenterException {
        Member member = memberMapper.findByMemberId(id);
        if (member == null) {
            throw new UCenterException(ErrorCode.MEMBER_NOT_FOUND);
        }
        return member;
    }

    public Member findIdcard(String idCard){
        return memberMapper.findIdCard(idCard);
    }



    @Transactional(rollbackFor = Exception.class)
    public Boolean SubmitAuthentication(ReqMemberAuthentication req) throws UCenterException {

        if (findIdcard(req.getIdCard()) != null) {
            throw new UCenterException(ErrorCode.ID_CARD_REPEAT);
        }

        Member member = this.findByMemberId(req.getMemberId());
        if (member.getRzStatus().equals(UcenterEnum.AuthStatus.SUC.getValue()) ||
                member.getRzStatus().equals(UcenterEnum.AuthStatus.OPING.getValue())
                ){
            throw new UCenterException(ErrorCode.AUTH_STATUS_ERROR);
        }

        //log record
        MemberSecurityLog log = new MemberSecurityLog();
        log.setMemberId(req.getMemberId());
        log.setType(10);
        log.setRemark("提交实名认证");
        log.setAddtime(new Date().getTime()/1000);
        memberSecurityLogMapper.insert(log);
        memberMapper.submitAuthentication(req.getMemberId(),req.getRealName(),req.getIdCard(),req.getFrontIdPic(),req.getBackIdPic(),new Date().getTime()/1000);
        return Boolean.TRUE;
    }




}
